package com.situ.mall.service.impl;

import com.situ.mall.mapper.CartMapper;
import com.situ.mall.mapper.OrderItemMapper;
import com.situ.mall.mapper.OrderMapper;
import com.situ.mall.pojo.entity.Order;
import com.situ.mall.pojo.entity.OrderItem;
import com.situ.mall.pojo.query.CartQuery;
import com.situ.mall.pojo.query.OrderQuery;
import com.situ.mall.pojo.vo.CartVO;
import com.situ.mall.pojo.vo.OrderVO;
import com.situ.mall.service.IOrderService;
import com.situ.mall.util.SnowFlake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private SnowFlake snowFlake;

    @Override
    public void add(Order order) {
        //使用雪花算法生成order的主键
        long orderNo = snowFlake.nextId();
        order.setOrderNo(orderNo);
        //整个订单总金额
        BigDecimal payment = BigDecimal.valueOf(0.0);
        //查找这个用户购物车里面勾选的要结算的商品
        CartQuery cartQuery = new CartQuery();
        cartQuery.setUserId(order.getUserId());
        cartQuery.setChecked(1);
        List<CartVO> cartVOList = cartMapper.list(cartQuery);
        for (CartVO cartVO : cartVOList) {
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderNo(orderNo);
            orderItem.setUserId(order.getUserId());
            orderItem.setProductId(cartVO.getProductId());
            orderItem.setProductName(cartVO.getProductName());
            orderItem.setProductImage(cartVO.getProductMainImage());
            orderItem.setCurrentUnitPrice(cartVO.getProductPrice());
            orderItem.setQuantity(cartVO.getQuantity());
            //orderItem.setTotalPrice(cartVO.getQuantity() * cartVO.getProductPrice());

            //计算当前商品的：价格*数量
            BigDecimal productPrice = cartVO.getProductPrice();
            BigDecimal quantity = BigDecimal.valueOf(cartVO.getQuantity());
            BigDecimal totalPrice = productPrice.multiply(quantity);
            orderItem.setTotalPrice(totalPrice);
            payment = payment.add(totalPrice);

            orderItemMapper.insertSelective(orderItem);

            //生成订单之后应该把购物车里面的商品删除
            cartMapper.deleteByPrimaryKey(cartVO.getId());
        }

        order.setPayment(payment);
        orderMapper.insertSelective(order);
    }

    @Override
    public List<OrderVO> list(OrderQuery orderQuery) {
        return orderMapper.list(orderQuery);
    }

    @Override
    public void updateStatus(Order order) {
        orderMapper.updateByPrimaryKey(order);
    }
}
